﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;
using System.Text;

namespace MVCFoto.BLL.Graphic
{
    public class Thumbnail
    {
        /// <summary>
        /// 生成封面
        /// </summary>
        /// <param name="oImagePath"></param>
        /// <returns></returns>
        public static bool ThumbnailCover(string oImagePath)
        {
            string coverImage = String.Format("{0}{3}{1}{3}{2}",
                                            Path.GetDirectoryName(oImagePath),
                                            "c",
                                            Path.GetFileName(oImagePath),
                                            Path.DirectorySeparatorChar);
            //生成过封面，直接返回
            if (File.Exists(coverImage))
                return true;
            //复制图片到c目录，作为封面
            if (File.Exists(oImagePath))
            {
                string newDir = Path.GetDirectoryName(coverImage);
                if (!Directory.Exists(newDir))
                    Directory.CreateDirectory(newDir);
                File.Copy(oImagePath, coverImage,true);

                bool result = true;
                foreach (ThumbnailSetting cover in MVCFotoSettings.ConverSize)
                {
                    result = result & GenerateThumbnail(coverImage, cover.Size, true, 85, cover.OverWrite);
                }
                return result;
            }
            else
                return false;
           
            
        }
        /// <summary>
        /// 缩略头像
        /// </summary>
        /// <param name="oImagePath"></param>
        /// <returns></returns>
        public static bool ThumbnailAvatar(string oImagePath)
        {
            //GenerateThumbnail(oImagePath, 128, true, 85,true);
            GenerateThumbnail(oImagePath, 96, true, 85, true);
            GenerateThumbnail(oImagePath, 64, true, 85, false);
            GenerateThumbnail(oImagePath, 48, true, 85, false);
            GenerateThumbnail(oImagePath, 32, true, 85, false);
            return true;
        }
        /// <summary>
        /// 按设置生成缩略图
        /// </summary>
        /// <param name="oImagePath"></param>
        public static void ThumbnailPhotos(string oImagePath)
        { 
            foreach(ThumbnailSetting thumb in MVCFotoSettings.ThumbnailSettings)
            {
                GenerateThumbnail(oImagePath, thumb.Size, thumb.Crop, 85, false);
            }

        }
        /// <summary>
        /// 根据exif信息旋转图片
        /// </summary>
        /// <param name="fileName">图片物理路径</param>
        /// <returns></returns>
        public static void RotateFlip(string fileName,ushort rotate)
        {
            if (rotate > 1)
            {  
                EncoderValue? eRotate = null;
                EncoderValue? eFlip = null;
                switch (rotate)
                {
                    case 2:
                        //水平镜像
                        eFlip = EncoderValue.TransformFlipHorizontal;
                        break;
                    case 3:
                        //180度
                        eRotate = EncoderValue.TransformRotate180;
                        break;
                    case 4:
                        //垂直镜像
                        eFlip = EncoderValue.TransformFlipVertical;
                        break;
                    case 5:
                        //水平镜像，270
                        eFlip = EncoderValue.TransformFlipHorizontal;
                        eRotate = EncoderValue.TransformRotate90;
                        break;
                    case 6:
                        //270
                        eRotate = EncoderValue.TransformRotate90;
                        break;
                    case 7:
                        //水平镜像,90
                        eFlip = EncoderValue.TransformFlipHorizontal;
                        eRotate = EncoderValue.TransformRotate270;
                        break;
                    case 8:
                        //90
                        eRotate = EncoderValue.TransformRotate270;
                        break;
                    default:
                        return;
                }
                EncoderParameters encParms = new EncoderParameters(1);
                System.Drawing.Imaging.Encoder Enc = System.Drawing.Imaging.Encoder.Transformation;
                ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
                //jpeg codec
                ImageCodecInfo ici = null;
                foreach (ImageCodecInfo codec in codecs)
                {
                    if (codec.MimeType == "image/jpeg")
                        ici = codec;
                }
                string tmpFile = fileName.Insert(fileName.LastIndexOf("."), ".tmp");
                Image img = Image.FromFile(fileName);
                try
                {
                    //保存旋转后的值到图片
                    PropertyItem pi = img.GetPropertyItem(0x112);
                    pi.Value[0] = 1;
                    img.SetPropertyItem(pi);
                }
                catch { }
                if (eRotate != null)
                { //rotate                    
                    EncoderParameter ep = new EncoderParameter(Enc, (long)eRotate);
                    encParms.Param[0] = ep;
                    img.Save(tmpFile, ici, encParms);
                }
                if (eFlip != null)
                {//flip                    
                    EncoderParameter ep = new EncoderParameter(Enc, (long)eFlip);
                    encParms.Param[0] = ep;
                    img.Save(tmpFile, ici, encParms);                 
                }                      
                img.Dispose();               
                img = null;
                if (File.Exists(tmpFile))
                {
                    File.Copy(tmpFile, fileName, true);
                    File.Delete(tmpFile);
                }
            }
         
        }

        #region thumbnail method
        /// <summary>
        /// 生成指定大小的缩略图,返回新文件名
        /// </summary>
        /// <param name="oImagePath">原图物理路径</param>
        /// <param name="size">缩略图大小(最大边)</param>
        /// <param name="corp">是否裁剪原图为正方形</param>
        /// <param name="level">缩略图质量(0-100)</param>
        /// <param name="overwrite">缩略图替换原图</param>
        public static bool GenerateThumbnail(string oImagePath, int size, bool corp, int level,bool overwrite)
        {
            Image source = Image.FromFile(oImagePath);
            
            int tWidth;//缩略图的宽度
            int tHeight;// 缩略图的高度
            
            //处理JPG质量的函数
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType == "image/jpeg")
                    ici = codec;               
            }
                                  
            EncoderParameters ep = new EncoderParameters();
            ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)level);

            string thumbImgFile = overwrite ? oImagePath.Replace(Path.GetExtension(oImagePath), ".jpg") : GetThumbnailPath(oImagePath, size);
           
            Rectangle cropRec = new Rectangle(0, 0, source.Width, source.Height);

            //最大边大于缩略图大小时才生成，否则直接将文件改名复制一份作为缩略图
            if (Math.Max(source.Width,source.Height) > size)
            {
                if (corp)
                {//裁剪区域
                    int min = Math.Min(source.Width, source.Height);
                    cropRec.X = (source.Width - min) / 2;
                    cropRec.Y = (source.Height - min) / 2;
                    cropRec.Width = cropRec.Height = min;
                    tWidth = tHeight = size;
                }
                else
                {
                    if (source.Width > source.Height)
                    {
                        tWidth = size;
                        tHeight = source.Height * tWidth / source.Width;
                    }
                    else
                    {
                        tHeight = size;
                        tWidth = source.Width * tHeight / source.Height;
                    }
                }

                Bitmap bm = new Bitmap(tWidth, tHeight);
                Graphics g = Graphics.FromImage(bm);
               
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.Clear(Color.White);
                g.DrawImage(source,
                    new Rectangle(0, 0, tWidth, tHeight),
                    cropRec,
                    GraphicsUnit.Pixel);                
                source.Dispose();

                bm.Save(thumbImgFile, ici, ep);
                g.Dispose();
                bm.Dispose();
            }
            else
            {//查接原图保存为缩略图
                
                
                if (oImagePath.ToLower() == thumbImgFile.ToLower())
                {//缩略图为原图，移动
                    //先关闭源文件
                    source.Dispose();  
                    File.Move(oImagePath, thumbImgFile);
                }
                else
                {//原图不是jpg图片，另存成jpg的缩略图
                    source.Save(thumbImgFile, ici, ep);
                    source.Dispose();  
                }
                  
            }
            if (File.Exists(thumbImgFile))
                return true;
            else
                return false;

        }
        #endregion

        /// <summary>
        /// 取得缩略图的存储位置
        /// 原图:c:/xxx.jpg
        /// size为400的缩略图:/s400/xxx.jpg
        /// </summary>
        /// <param name="oImagePath">原图地址</param>
        /// <param name="size">大小</param>
        /// <returns></returns>
        static string GetThumbnailPath(string oImagePath, int size)
        {
            string thumbPath = Path.Combine(Path.GetDirectoryName(oImagePath), String.Format("s{0}", size));
            if (!Directory.Exists(thumbPath))
                Directory.CreateDirectory(thumbPath);
            //缩略图均为jpg
            return Path.Combine(thumbPath, Path.GetFileNameWithoutExtension(oImagePath) + ".jpg");

        }
        /// <summary>
        /// 取得封面的路径
        /// </summary>
        /// <param name="oUrl"></param>
        /// <returns></returns>
        public static string GetCoverPhotoUrl(string oUrl)
        {
            if (String.IsNullOrEmpty(oUrl))
                return string.Empty;
            else
            {
                oUrl = oUrl.Replace("\\", "/");
                return oUrl.Insert(oUrl.LastIndexOf("/"), "/c");
            }
        }


    }
}
